﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Ultilities;
using MvcApplication2.Ultilities.Enums;

namespace MvcApplication2.Attributes
{
    public class AccessAuthorizeAttribute : AuthorizeAttribute
    {
        private readonly List<RoleKey> canAccessRoleKey;

        public AccessAuthorizeAttribute(params RoleKey[] roleKeys)
        {
            canAccessRoleKey = new List<RoleKey>(roleKeys);
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var roleKeys = HttpContext.Current.Session[Constant.RoleKeys] as List<RoleKey>;
            var canAccess = roleKeys.Any(roleKey => canAccessRoleKey.Contains(roleKey));
            if (!canAccess)
            {
                filterContext.Result = new RedirectResult("~/Error/AccessDenied");
            }
            base.OnAuthorization(filterContext);
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectResult("~/Error/AccessDenied");
        }
    }
}